/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package code.google.pigfly;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.pig.PigException;

/**
 */
public class PigflyMetaStore {
  public static final Log LOG = LogFactory.getLog(PigflyMetaStore.class);

  private HiveMetaStoreClient client = null;
  private Map<String, Table> tableCache = new HashMap<String, Table>();

  // singleton pattern
  private static PigflyMetaStore instance;

  public static PigflyMetaStore getInstance() throws IOException {
    if (instance == null) {
      instance = new PigflyMetaStore();
    }
    return instance;
  }

  protected PigflyMetaStore() throws IOException {
    HiveConf hiveConf = new HiveConf(PigflyMetaStore.class);
    try {
      client = new HiveMetaStoreClient(hiveConf, null);
    } catch (MetaException me) {
      String errMsg =
          "Could not instantiate a HiveMetaStoreClient connecting to meta server";
      LOG.warn(errMsg, me);
      throw new PigException(errMsg + me.getMessage(), 1112);
    }
  }

  public Table getTable(final String fullTableName) throws IOException {
    // check if exists in the cache
    Table table = tableCache.get(fullTableName);
    if (table != null)
      return table;
    // not in the cache
    String[] tokens = fullTableName.split("\\.");
    String dbName = "default";
    String tableName = null;
    if (tokens.length == 1) {
      tableName = tokens[0];
    } else if (tokens.length == 2) {
      dbName = tokens[0];
      tableName = tokens[1];
    } else {
      String locationErrMsg =
          "The input location in load statement " + "should be of the form "
              + "<databasename>.<table name> or <table name>. Got "
              + fullTableName;
      throw new IOException(locationErrMsg);
    }

    try {
      table = client.getTable(dbName, tableName);
    } catch (NoSuchObjectException nsoe) {
      throw new PigException("Table not found : " + nsoe.getMessage(), 1113);
    } catch (Exception e) {
      throw new IOException(e);
    }
    return table;
  }

  public List<Partition> listPartitionsByFilter(final String dbname,
      final String name, final String filter) throws IOException {
    List<Partition> partitions = null;
    // try {
    // partitions = client.listPartitionsByFilter(dbname, name, filter);
    // } catch (NoSuchObjectException nsoe) {
    // throw new PigException("Table not found : " + nsoe.getMessage(), 1113);
    // } catch (Exception e) {
    // throw new IOException(e);
    // }
    return partitions;
  }
}
